<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>别抽我，谢谢！</title>
    <style>
        /* 基础样式 */
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .app {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2c3e50;
            text-align: center;
        }

        /* 班级选择 */
        .class-selector {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        select, button {
            padding: 8px 12px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
        button {
            background: #3498db;
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        button:hover {
            background: #2980b9;
        }

        /* 座位矩阵 */
        .matrix {
            display: grid;
            gap: 10px;
            margin: 20px 0;
        }
        .seat {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #2ecc71;
            color: white;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
        }
        .seat.empty {
            background: #ecf0f1;
            color: #7f8c8d;
        }
        .seat.highlight {
            background: #e74c3c;
            transform: scale(1.1);
            box-shadow: 0 0 15px #f39c12;
        }

        /* 操作按钮 */
        .controls {
            display: flex;
            gap: 10px;
            justify-content: center;
        }
        #drawBtn {
            background: #e74c3c;
        }
        #saveBtn {
            background: #27ae60;
        }

        /* 弹窗样式 */
        .dialog {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background: white;
            box-shadow: 0 0 20px rgba(0,0,0,0.2);
            border-radius: 10px;
            z-index: 100;
        }
        .dialog input {
            display: block;
            margin: 10px 0;
            padding: 8px;
            width: 200px;
        }
        .dialog button {
            width: 100%;
            margin-top: 10px;
        }
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 99;
        }
        /* 添加到 style 部分 */
        #exportBtn {
            background: #9b59b6;
        }
        #importBtn {
            background: #3498db;
        }
        #exportBtn:hover {
            background: #8e44ad;
        }
        #importBtn:hover {
            background: #2980b9;
        }
        #renameClass {
            background: #f39c12;
        }
        #renameClass:hover {
            background: #e67e22;
        }
        /* 批量删除按钮样式 */
        #batchDelete {
            background: #e74c3c;
            /* margin-left: 10px; */
        }
        #batchDelete:hover {
            background: #c0392b;
        }

        /* 批量删除列表项样式 */
        .batch-delete-item {
            display: flex;
            align-items: center;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .batch-delete-item input {
            margin-right: 10px;
        }
        /* 批量操作按钮样式 */
        .batch-action-btn {
            padding: 5px 10px;
            margin-right: 5px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }
        .batch-action-btn:hover {
            background: #2980b9;
        }

        /* 选中项高亮样式 */
        .batch-delete-item.selected {
            background-color: #f5f5f5;
        }

        /* ================= 移动端适配 ================= */
        @media (max-width: 768px) {
            body {
                padding: 10px;
                font-size: 14px;
            }

            .app {
                padding: 15px;
            }

            /* 班级选择器调整 */
            .class-selector {
                flex-direction: column;
            }

            /* 按钮优化 */
            .class-selector button, .controls button {
                flex: 1 0 auto;
                min-height: 40px;
                margin: 3px 0;
            }

            /* 图标化按钮 */
            #addClass > span, #renameClass > span, 
            #deleteClass > span, #batchDelete > span {
                display: none;
            }
            /* #addClass::after { content: "+"; }
            #renameClass::after { content: "✏️"; }
            #deleteClass::after { content: "🗑️"; }
            #batchDelete::after { content: "🗑️🗑️"; } */

            /* 座位矩阵调整 */
            .matrix {
                gap: 5px;
            }
            .seat {
                width: 12vw;
                height: 12vw;
                min-width: 35px;
                min-height: 35px;
            }

            /* 弹窗优化 */
            .dialog {
                width: 90vw;
                padding: 15px;
            }

            /* 折叠式控制按钮 */
            .controls {
                position: relative;
            }
            .controls-collapser {
                display: block;
                text-align: center;
                font-size: 24px;
                cursor: pointer;
            }
            .controls.hidden button:not(:first-child) {
                display: none;
            }
        }
    </style>
</head>
<body>
<div class="app">
    <h1>抽！抽！抽！</h1>

    <!-- 班级选择 --><!-- 班级选择 -->
    <div class="class-selector">
        <select id="classSelector">
            <option value="">-- 请选择班级 --</option>
        </select>
        <button id="addClass">添加班级</button>
        <button id="renameClass">修改名称</button>
        <button id="deleteClass">删除班级</button>
        <button id="batchDelete">批量删除</button>
        <button id="exportBtn">导出数据</button>
        <button id="importBtn">导入数据</button>
        <input type="file" id="fileInput" accept=".json" style="display: none;">
    </div>

    <!-- 座位矩阵 --><!-- 座位矩阵 -->
    <div id="matrix" class="matrix"></div>

    <!-- 操作按钮 --><!-- 操作按钮 -->
    <div class="controls">
        <button id="drawBtn">随机抽人</button>
        <button id="saveBtn">保存修改</button>
    </div>

    <!-- 添加班级弹窗 --><!-- 添加班级弹窗 -->
    <div id="overlay" class="overlay"></div>
    <div id="dialog" class="dialog">
        <h3>添加新班级</h3>
        <input type="text" id="className" placeholder="班级名称">
        <input type="number" id="rows" placeholder="行数" min="1" max="10">
        <input type="number" id="cols" placeholder="列数" min="1" max="10">
        <button id="confirmAdd">确认添加</button>
        <button id="cancelDialog" style="background: #95a5a6;">取消</button>
    </div>

    <!-- 改名弹窗 -->
    <div id="renameDialog" class="dialog">
        <h3>修改班级名称</h3>
        <input type="text" id="newClassName" placeholder="输入新名称">
        <button id="confirmRename">确认修改</button>
        <button id="cancelRename" style="background: #95a5a6;">取消</button>
    </div>

    <!-- 批量删除弹窗 -->
    <div id="batchDeleteDialog" class="dialog">
        <h3>批量删除班级</h3>
        <div style="margin-bottom: 10px;">
            <button id="selectAllBtn" class="batch-action-btn">全选</button>
            <button id="invertSelectBtn" class="batch-action-btn">反选</button>
        </div>
        <div id="batchDeleteList" style="max-height: 200px; overflow-y: auto; margin: 10px 0; border: 1px solid #ddd; padding: 5px;"></div>
        <button id="confirmBatchDelete" style="background: #e74c3c;">确认删除选中项</button>
        <button id="cancelBatchDelete" style="background: #95a5a6;">取消</button>
    </div>
</div>

<script>
    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
        initClassSelector();
        loadCurrentClass();
        setupEventListeners();
    });

    // 班级数据结构
    let classes = JSON.parse(localStorage.getItem('classes')) || {};
    let currentClassId = localStorage.getItem('currentClassId') || null;

    // 初始化班级选择器
    function initClassSelector() {
        const selector = document.getElementById('classSelector');
        selector.innerHTML = '<option value="">-- 请选择班级 --</option>' +
            Object.keys(classes).map(id =>
                `<option value="${id}" ${id === currentClassId ? 'selected' : ''}>${classes[id].name}</option>`
            ).join('');
    }

    // 加载当前班级
    function loadCurrentClass() {
        const matrix = document.getElementById('matrix');
        matrix.innerHTML = '';

        if (!currentClassId || !classes[currentClassId]) {
            matrix.innerHTML = '<p>请选择或创建班级</p>';
            return;
        }

        const cls = classes[currentClassId];
        matrix.style.gridTemplateColumns = `repeat(${cls.cols}, 1fr)`;

        for (let r = 0; r < cls.rows; r++) {
            for (let c = 0; c < cls.cols; c++) {
                const seat = document.createElement('div');
                seat.className = 'seat';
                seat.textContent = `${c+1}-${r+1}`;
                seat.dataset.pos = `${r}-${c}`;

                if (cls.emptySeats && cls.emptySeats.includes(`${r}-${c}`)) {
                    seat.classList.add('empty');
                }

                seat.addEventListener('click', () => {
                    seat.classList.toggle('empty');
                });

                matrix.appendChild(seat);
            }
        }
    }

    // 设置事件监听
    function setupEventListeners() {
        // 班级选择
        document.getElementById('classSelector').addEventListener('change', (e) => {
            currentClassId = e.target.value;
            localStorage.setItem('currentClassId', currentClassId);
            loadCurrentClass();
        });

        // 添加班级
        document.getElementById('addClass').addEventListener('click', showDialog);

        // 删除班级
        document.getElementById('deleteClass').addEventListener('click', () => {
            if (!currentClassId) return alert('请先选择班级');
            if (!confirm(`确定要删除【${classes[currentClassId].name}】吗？`)) return;

            delete classes[currentClassId];
            localStorage.setItem('classes', JSON.stringify(classes));

            if (Object.keys(classes).length === 0) {
                currentClassId = null;
                localStorage.removeItem('currentClassId');
            } else {
                currentClassId = Object.keys(classes)[0];
                localStorage.setItem('currentClassId', currentClassId);
            }

            initClassSelector();
            loadCurrentClass();
        });

        // 随机抽人
        document.getElementById('drawBtn').addEventListener('click', drawStudent);

        // 保存修改
        document.getElementById('saveBtn').addEventListener('click', saveChanges);

        // 弹窗控制
        document.getElementById('cancelDialog').addEventListener('click', hideDialog);
        document.getElementById('confirmAdd').addEventListener('click', addNewClass);

        // 改名按钮监听
        document.getElementById('renameClass').addEventListener('click', showRenameDialog);
        document.getElementById('confirmRename').addEventListener('click', renameClass);
        document.getElementById('cancelRename').addEventListener('click', hideRenameDialog);

        // 批量删除功能
        document.getElementById('batchDelete').addEventListener('click', showBatchDeleteDialog);
        document.getElementById('confirmBatchDelete').addEventListener('click', confirmBatchDelete);
        document.getElementById('cancelBatchDelete').addEventListener('click', hideBatchDeleteDialog);
        document.getElementById('selectAllBtn').addEventListener('click', selectAllClasses);
        document.getElementById('invertSelectBtn').addEventListener('click', invertSelection);
    }

    // 随机抽人
    function drawStudent() {
        if (!currentClassId) return alert('请先选择班级');

        const seats = document.querySelectorAll('.seat:not(.empty)');
        if (seats.length === 0) return alert('没有可抽选的学生！');

        let counter = 0;
        const interval = setInterval(() => {
            // 清除之前的高亮
            document.querySelectorAll('.seat').forEach(s => s.classList.remove('highlight'));

            // 随机高亮
            const randomSeat = seats[Math.floor(Math.random() * seats.length)];
            randomSeat.classList.add('highlight');

            if (++counter > 15) {
                clearInterval(interval);
                setTimeout(() => {
                    alert(`抽中: ${randomSeat.textContent}`);
                }, 300);
            }
        }, 100);
    }

    // 保存修改
    function saveChanges() {
        if (!currentClassId) return;

        const emptySeats = [];
        document.querySelectorAll('.seat.empty').forEach(seat => {
            emptySeats.push(seat.dataset.pos);
        });

        classes[currentClassId].emptySeats = emptySeats;
        localStorage.setItem('classes', JSON.stringify(classes));
        alert('保存成功！');
    }

    // 显示弹窗
    function showDialog() {
        document.getElementById('overlay').style.display = 'block';
        document.getElementById('dialog').style.display = 'block';
        document.getElementById('className').value = '';
        document.getElementById('rows').value = '';
        document.getElementById('cols').value = '';
    }

    // 隐藏弹窗
    function hideDialog() {
        document.getElementById('overlay').style.display = 'none';
        document.getElementById('dialog').style.display = 'none';
    }

    // 添加新班级
    function addNewClass() {
        const name = document.getElementById('className').value.trim();
        const rows = parseInt(document.getElementById('rows').value);
        const cols = parseInt(document.getElementById('cols').value);

        if (!name) return alert('请输入班级名称！');
        if (isNaN(rows)) return alert('请输入有效行数！');
        if (isNaN(cols)) return alert('请输入有效列数！');

        const newId = Date.now().toString();
        classes[newId] = {
            name,
            rows,
            cols,
            emptySeats: []
        };
        localStorage.setItem('classes', JSON.stringify(classes));

        currentClassId = newId;
        localStorage.setItem('currentClassId', newId);

        hideDialog();
        initClassSelector();
        loadCurrentClass();
    }

    // 导出数据（非覆盖式）
    document.getElementById('exportBtn').addEventListener('click', () => {
        const data = {
            version: "1.0",
            classes: classes,
            currentClassId: currentClassId,
            timestamp: new Date().toISOString()
        };

        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `抽人系统备份_${new Date().toLocaleString().replace(/[/:]/g, '-')}.json`;
        a.click();
        setTimeout(() => URL.revokeObjectURL(url), 100);
    });

    // 导入数据（合并而非覆盖）
    document.getElementById('importBtn').addEventListener('click', () => {
        document.getElementById('fileInput').click();
    });

    document.getElementById('fileInput').addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (event) => {
            try {
                const importedData = JSON.parse(event.target.result);

                // 1. 数据验证增强版
                if (!importedData.classes || typeof importedData.classes !== 'object') {
                    throw new Error("无效的数据格式：classes 必须是对象");
                }

                // 2. 深度合并班级数据
                let importedCount = 0;
                const conflictNames = new Set(); // 记录冲突的班级名

                Object.entries(importedData.classes).forEach(([classId, classInfo]) => {
                    // 2.1 检查是否已存在完全相同的班级ID
                    if (classes[classId]) {
                        // 存在冲突时创建新ID（保留原数据）
                        const newId = Date.now() + Math.random().toString(36).substr(2, 5);
                        classes[newId] = {
                            ...classInfo,
                            name: `${classInfo.name}_导入_${new Date().getHours()}${new Date().getMinutes()}`
                        };
                        conflictNames.add(classInfo.name);
                    } else {
                        // 直接添加新班级
                        classes[classId] = classInfo;
                    }
                    importedCount++;
                });

                // 3. 更新存储
                localStorage.setItem('classes', JSON.stringify(classes));

                // 4. 如果当前没有选中班级，且导入数据有currentClassId，则设置
                if (!currentClassId && importedData.currentClassId) {
                    currentClassId = importedData.currentClassId;
                    localStorage.setItem('currentClassId', currentClassId);
                }

                // 5. 刷新UI
                initClassSelector();
                loadCurrentClass();

                // 6. 显示详细导入报告
                let message = `成功导入 ${importedCount} 个班级`;
                if (conflictNames.size > 0) {
                    message += `\n（${conflictNames.size} 个班级因重名已添加后缀：${[...conflictNames].join('、')}）`;
                }
                alert(message);

            } catch (err) {
                alert(`导入失败：${err.message}\n\n请检查文件格式是否正确`);
                console.error("导入错误详情：", err);
            }
            e.target.value = ''; // 清除文件选择
        };
        reader.readAsText(file);
    });

    // 显示改名弹窗
    function showRenameDialog() {
        if (!currentClassId) return alert('请先选择要修改的班级');

        document.getElementById('overlay').style.display = 'block';
        document.getElementById('renameDialog').style.display = 'block';
        document.getElementById('newClassName').value = classes[currentClassId].name;
        document.getElementById('newClassName').focus();
    }

    // 隐藏改名弹窗
    function hideRenameDialog() {
        document.getElementById('overlay').style.display = 'none';
        document.getElementById('renameDialog').style.display = 'none';
    }

    function renameClass() {
        const newName = document.getElementById('newClassName').value.trim();
        const classObj = classes[currentClassId];

        // 验证输入
        if (!newName) return alert('班级名称不能为空');
        if (newName === classObj.name) {
            hideRenameDialog();
            return;
        }

        // 检查重名
        const isNameExist = Object.values(classes).some(
            cls => cls.name === newName && cls !== classObj
        );
        if (isNameExist) return alert('已存在同名班级');

        // 执行改名
        classObj.name = newName;
        localStorage.setItem('classes', JSON.stringify(classes));

        // 更新UI
        initClassSelector();
        hideRenameDialog();
        alert(`已成功修改为：${newName}`);
    }

    function showBatchDeleteDialog() {
        if (Object.keys(classes).length === 0) {
            return alert('没有可删除的班级');
        }

        const container = document.getElementById('batchDeleteList');
        container.innerHTML = '';

        // 创建可勾选的班级列表
        Object.entries(classes).forEach(([id, classInfo]) => {
            const item = document.createElement('div');
            item.className = 'batch-delete-item';
            item.innerHTML = `
            <input type="checkbox" id="batch-${id}" class="batch-checkbox">
            <label for="batch-${id}">${classInfo.name} (${classInfo.rows}×${classInfo.cols})</label>
        `;
            container.appendChild(item);
        });

        document.getElementById('overlay').style.display = 'block';
        document.getElementById('batchDeleteDialog').style.display = 'block';
    }

    function hideBatchDeleteDialog() {
        document.getElementById('overlay').style.display = 'none';
        document.getElementById('batchDeleteDialog').style.display = 'none';
    }

    function confirmBatchDelete() {
        const checkboxes = document.querySelectorAll('.batch-checkbox:checked');
        if (checkboxes.length === 0) return alert('请至少选择一个班级');

        if (!confirm(`确定要删除选中的 ${checkboxes.length} 个班级吗？`)) return;

        // 收集要删除的ID
        const idsToDelete = Array.from(checkboxes).map(checkbox =>
            checkbox.id.replace('batch-', '')
        );

        // 执行删除
        idsToDelete.forEach(id => {
            delete classes[id];
            if (currentClassId === id) currentClassId = null;
        });

        // 更新存储
        localStorage.setItem('classes', JSON.stringify(classes));
        if (!currentClassId && Object.keys(classes).length > 0) {
            currentClassId = Object.keys(classes)[0];
            localStorage.setItem('currentClassId', currentClassId);
        }

        // 刷新UI
        initClassSelector();
        loadCurrentClass();
        hideBatchDeleteDialog();
        alert(`已删除 ${idsToDelete.length} 个班级`);
    }

    function selectAllClasses() {
        const checkboxes = document.querySelectorAll('.batch-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = true;
            checkbox.closest('.batch-delete-item').classList.add('selected');
        });
        updateSelectionCount();
    }

    function invertSelection() {
        const checkboxes = document.querySelectorAll('.batch-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = !checkbox.checked;
            checkbox.closest('.batch-delete-item').classList.toggle('selected', checkbox.checked);
        });
        updateSelectionCount();
    }

    function showBatchDeleteDialog() {
        if (Object.keys(classes).length === 0) {
            return alert('没有可删除的班级');
        }

        const container = document.getElementById('batchDeleteList');
        container.innerHTML = '';

        Object.entries(classes).forEach(([id, classInfo]) => {
            const item = document.createElement('div');
            item.className = 'batch-delete-item';
            item.innerHTML = `
            <input type="checkbox" id="batch-${id}" class="batch-checkbox">
            <label for="batch-${id}">${classInfo.name} (${classInfo.rows}×${classInfo.cols})</label>
        `;
            container.appendChild(item);
        });

        // 添加复选框变化监听
        document.querySelectorAll('.batch-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                this.closest('.batch-delete-item').classList.toggle('selected', this.checked);
                updateSelectionCount();
            });
        });

        document.getElementById('overlay').style.display = 'block';
        document.getElementById('batchDeleteDialog').style.display = 'block';
        updateSelectionCount(); // 初始化计数
    }

    function updateSelectionCount() {
        const selectedCount = document.querySelectorAll('.batch-checkbox:checked').length;
        const totalCount = Object.keys(classes).length;
        const btn = document.getElementById('confirmBatchDelete');
        btn.textContent = `确认删除选中项 (${selectedCount}/${totalCount})`;

        // 根据选择状态禁用/启用按钮
        btn.disabled = selectedCount === 0;
    }

    function confirmBatchDelete() {
        const checkboxes = document.querySelectorAll('.batch-checkbox:checked');
        const classNames = Array.from(checkboxes).map(cb =>
            classes[cb.id.replace('batch-', '')].name
        ).join('、');

        if (!confirm(`确定要删除以下班级吗？\n\n${classNames}`)) return;

        // ...原有删除逻辑...
        // 收集要删除的ID
        const idsToDelete = Array.from(checkboxes).map(checkbox =>
            checkbox.id.replace('batch-', '')
        );

        // 执行删除
        idsToDelete.forEach(id => {
            delete classes[id];
            if (currentClassId === id) currentClassId = null;
        });

        // 更新存储
        localStorage.setItem('classes', JSON.stringify(classes));
        if (!currentClassId && Object.keys(classes).length > 0) {
            currentClassId = Object.keys(classes)[0];
            localStorage.setItem('currentClassId', currentClassId);
        }

        // 刷新UI
        initClassSelector();
        loadCurrentClass();
        hideBatchDeleteDialog();
        alert(`已删除 ${idsToDelete.length} 个班级`);
    }

    // ================= 移动端专属功能 =================
    // 1. 动态布局调整
    function checkMobileLayout() {
        const isMobile = window.innerWidth <= 768;
        document.body.classList.toggle('mobile-mode', isMobile);

        if (isMobile) {
            // 批量删除列表高度调整
            const batchList = document.getElementById('batchDeleteList');
            if (batchList) batchList.style.maxHeight = '50vh';
        }
    }

    // 2. 控制按钮折叠逻辑
    // function setupMobileControls() {
    //     const controls = document.querySelector('.controls');
    //     if (!controls) return;

    //     const collapser = document.createElement('div');
    //     collapser.className = 'controls-collapser';
    //     collapser.innerHTML = '⋯';
    //     controls.prepend(collapser);

    //     collapser.addEventListener('click', () => {
    //         controls.classList.toggle('hidden');
    //     });
    // }

    // // 3. 摇一摇抽人（可选）
    // function setupShakeDetection() {
    //     if (!('ondevicemotion' in window)) return;

    //     let lastShake = 0;
    //     window.addEventListener('devicemotion', (e) => {
    //         const acc = e.accelerationIncludingGravity;
    //         if (!acc) return;

    //         const shake = Math.abs(acc.x) + Math.abs(acc.y) + Math.abs(acc.z);
    //         if (shake > 35 && Date.now() - lastShake > 2000) {
    //             lastShake = Date.now();
    //             document.getElementById('drawBtn').click();
    //         }
    //     });
    // }

    // 初始化移动端功能
    function initMobileFeatures() {
        checkMobileLayout();
        setupMobileControls();
        setupShakeDetection();
        window.addEventListener('resize', checkMobileLayout);
    }

    // 在DOM加载后调用
    document.addEventListener('DOMContentLoaded', initMobileFeatures);
</script>
</body>
</html>
